package com.wooming.myserver.security;

import com.wooming.myserver.constant.Security;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.util.HexFormat;

/**
 * 密码加密
 *
 * @author Wooming 2025/05/20
 */
@Component
public class PasswordEncryption {
    // 依赖注入算法与密钥(失效,原因未知)
    @Value("${server.encryption.algorithm}")
    private static final String ALGORITHM = Security.ALGORITHM.getValue();
    @Value("${server.encryption.key}")
    private static final String secretKey = Security.KEY.getValue();
    // 形成密钥
    private static final SecretKeySpec key = new SecretKeySpec(secretKey.getBytes(), ALGORITHM);
    public static String encrypt(String password) throws Exception {
        // 加密
        Mac mac  = Mac.getInstance(ALGORITHM);
        mac.init(key);
        byte[] rawHmac = mac.doFinal(password.getBytes());
        return HexFormat.of().formatHex(rawHmac);
    }

    public static boolean verify(String password, String encryptedPassword) throws Exception {
        // 验证
        return encrypt(password).equals(encryptedPassword);
    }
}
